from django import forms

from .bootstrapbase import BootStrapForm
from web import models
from utils.tencent.cos import CosTencent



class ProjectDeleteModelForm(BootStrapForm, forms.ModelForm):
    """ 删除项目ModelForm """

    class Meta:
        model = models.Project
        fields = ['name', ]

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_name(self):
        cos = CosTencent()
        name = self.cleaned_data['name']
        # 校验name信息
        # 0 删除存储桶，要先删除桶中的所有文件和碎片，才能删除桶
        # 1 输入的项目名要在数据库中存在
        # 2 只有项目的创建者才能够删除项目名称

        delete_project_object = models.Project.objects.filter(name=name).first()
        if not delete_project_object:
            self.add_error('name', '项目不存在')
        else:
            if self.request.login_user.user != delete_project_object.creator:
                self.add_error('name', '非项目创建者不能删除项目')
            else:
                delete_project_object.delete()
        cos.delete_full_bucket(bucket_name=self.request.login_user.project.bucket_name)
        return name

